// pages/index/index.js
const utils = require('../../utils/custom.js')
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    /**
     * 1: home
     * 2: add
     * 3: check
     */
    status: 1,
    input: "",
    checkList: [],
    goals:[],
    checkIndex: 0,
    title:["", "自律助手", "添加打卡目标", "选择完成状态"]
  },
  clock:function() {
    let _that = this
    let old = wx.getStorageSync('checkday')
    console.log(old)
    let now = new Date()
    if(old != null && old != "" && !(old instanceof Date)) {
      console.log("old转型")
      old = new Date(old)
    }
    console.log("old类型数据Date？", old instanceof Date)
    if(old != null && old != "" &&
       old.getMonth() == now.getMonth() 
       && old.getDate() == now.getDate()) {
      wx.showToast({
        title: '很棒！明天再来吧~',
        icon: "none"
      })
      return;
    }
    // let res = utils.userLogin();
    if(app.globalData.globalToken == null) {
      console.log("用户未登录")
      this.setData({
        show_tar: true
      })
      return;
    }
    wx.request({
      url: 'https://birdy.run/sc/goal/get_user_all',
      method: "GET",
      data: {
        token: app.globalData.globalToken
      },
      success: function(res) {
        console.log(res)
        var result = res.data
        if(result.res == 200) {
          let ret = result.data.goal;
          if(ret.length == 0) {
            _that.setData({
              show_add: true
            })
          } else {
            _that.setData({
              checkList: ret,
              status: 3,
            })
          }
        } else {
          wx.showToast({
            title: '获取打卡信息失败，请重新启动小程序',
            icon: "none"
          })
        }
      },
      fail: function(res) {
        console.log(res)
        wx.showToast({
          title: '服务器繁忙！',
          icon: "error"
        })
        wx.hideLoading()
      }
    })
  },
  login: function() {
    let _this = this
    if(!app.globalData.globalToken) {
      wx.getUserProfile({
        desc: "在交互中展示头像区分用户",
        success: function(info) {
          console.log(info)
          wx.showLoading({
            title: '正在登录',
          })
          wx.login({
            success(res) {
              console.log(res)
              if(res.code) {
                wx.request({
                  // ?code=${res.code}
                  url: `https://birdy.run/sc/user/login_with_info`,
                  method: "POST",
                  data: {
                    code: res.code,
                    user_info: info.userInfo
                  },
                  success:function(res) {
                    console.log(res)
                    if(res.data.res == 200 && res.data.data.token) {
                      wx.setStorage({
                        key: "token",
                        data: res.data.data.token,
                        success: function(e) {
                          console.log("设置缓存成功")
                          app.globalData.globalToken = res.data.data.token
                          _this.setData({
                            show_tar: false
                          })
                          wx.showToast({
                            title: '登录成功',
                            icon: 'success'
                          })

                        }
                      })
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: res.data.msg,
                        icon: 'error'
                      })
                    }
                  },
                  fail: function(res) {
                    wx.hideLoading()
                    wx.showToast({
                      title: '网络异常，请重试',
                      icon: 'error'
                    })
                    console.log(res)
                  }
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '网络异常，请重试',
                  icon: 'error'
                })
                console.log("login failed")
              }
            },
            fail(res) {
              wx.hideLoading()
              console.error("login failed")
              console.log(res)
            }
          })
        }
      })
    }else {
      wx.showToast({
        title: '您已登录',
        icon: "success"
      })
    }
  },
  add: function() {
    this.setData({
      status: 2,
      show_add: false
    })
  },
  my: function() {
    this.setData({
      show_add: true
    })
    // wx.redirectTo({
    //   url: '../my/my',
    // })
  },
  goal_input: function(res) {
    console.log(res)
    if(res.detail.value.length > 30) {
      wx.showToast({
        title: '字数太多啦',
        icon: 'none'
      })
    } else {
      this.setData({
        input: res.detail.value
      })
    }
  },
  next: function() {
    var that = this;
    if(this.data.input.length < 2) {
      wx.showToast({
        title: '再多点字？',
        icon: "error"
      })
      return;
    }
    if(app.globalData.globalToken == null) {
      console.log("用户未登录")
      this.setData({
        show_tar: true
      })
      return;
    }
    wx.request({
      url: 'https://birdy.run/sc/goal/add',
      method: "POST",
      data: {
        name: that.data.input,
        creator: app.globalData.globalToken
      },
      success: function(ret) {
        console.log(ret)
        if(ret.data.res == 200) {
          wx.showToast({
            title: '添加成功',
            icon: "success"
          })
          that.setData({
            status: 1
          })
        }else {
          wx.showToast({
            title: '添加失败',
            icon: "error"
          })
        }
      }
    })
  },
  clear: function() {
    this.setData({
      goals: [],
      checkIndex: 0,
    })
  },
  target_do: function(data) {
    let that = this
    let tmp = {}
    tmp.finished = data.target.dataset.finished
    tmp.goal = {}
    tmp.goal.id = this.data.checkList[this.data.checkIndex].id
    this.data.goals.push(tmp)
    if(this.data.checkIndex == this.data.checkList.length - 1) {
      console.log(this.data.goals)
      wx.showLoading({
        title: '正在打卡',
      })
      wx.request({
        url: 'https://birdy.run/sc/check/add',
        method: "POST",
        data: {
          token: app.globalData.globalToken,
          goals: that.data.goals
        },
        success: function(res) {
          if(res.data.res == 200) {
            wx.setStorage({
              key: "checkday",
              data: new Date(),
            })
            wx.setStorage({
              key: "comment",
              data: res.data.data.comment
            })
            that.setData({
              comment: res.data.data.comment
            })
            wx.showToast({
              title: '打卡成功',
              icon: "success"
            })
          } else if (res.data.res == 1001) {
            wx.showToast({
              title: '今天打过卡了',
              icon: "error"
            })
          } else {
            wx.showToast({
              title: '服务拥挤请重试',
              icon: "error"
            })
          }
        },
        fail: function() {
          wx.showToast({
            title: '网络错误',
          })
        }
      })
      this.setData({
        status: 1
      })
      that.clear()
    } else {
      this.setData({
        checkIndex: this.data.checkIndex + 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    utils.setBarHeight(that);
    utils.setAppToken();
    let old = wx.getStorageSync('checkday')
    let now = new Date();
    let comment;
    if(old != null && old != "" && !old instanceof Date) {
      old = new Date(old)
    }
    console.log("old类型数据Date？", old instanceof Date)
    if(old != null && old != "" &&
       old.getMonth() == now.getMonth() 
       && old.getDate() == now.getDate()) {
      console.log('今天已经打卡')
      comment = wx.getStorageSync('comment')
    } else {
      console.log('今天暂未打卡')
      comment = "O"
    }
    this.setData({
      comment: comment
    })
    console.log(this.data.comment)
    console.log(old)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})